using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Acms.WebControls
{
    [ToolboxData("<{0}:TextBoxField runat=server></{0}:TextBoxField>")]
    public class TextBoxField : BaseDataField
    {
        protected override DataControlField CreateField()
        {
            return new TextBoxField();
        }

        private Unit width;
        public Unit Width
        {
            get { return width; }
            set { width = value; }
        }

        private int maxLength;
        public int MaxLength
        {
            get { return maxLength; }
            set { maxLength = value; }
        }

        protected override void InitEditControls(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
        {
            TextBox txt = new TextBox();
            txt.ID = GetUniqueId(rowIndex, "txt");
            txt.Width = this.Width;
            txt.MaxLength = MaxLength;

            cell.Controls.Add(txt);
        }

        protected override void DataBindEditControls(DataControlFieldCell cell, object dataItem, int dataItemIndex, int displayIndex)
        {
            TextBox txt = cell.Controls[0] as TextBox;
            if (txt != null)
            {
                object val = DataBinder.Eval(dataItem, DataField);
                if (val != null)
                {
                    txt.Text = val.ToString();
                }
            }
        }

        public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
        {
            if(cell.Controls.Count > 0 && !string.IsNullOrEmpty(this.DataField))
            {
                TextBox txt = cell.Controls[0] as TextBox;
                if (txt != null)
                {
                    dictionary.Add(this.DataField, txt.Text);
                }
            }
        }
    }
}
